package com.example.sherlockzhong.plush_v2.Models;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;

import com.example.sherlockzhong.plush_v2.Constant;
import com.example.sherlockzhong.plush_v2.Constants.UrlConstant;
import com.example.sherlockzhong.plush_v2.Utils.NetworkUtils;

import org.json.JSONObject;
import org.json.JSONTokener;

/*
 * Created by SherlockZhong on 9/11/14.
 */

public class UserModel {

    public static String getStudentId() {
        return Constant.STUDENT_ID;
    }

    public static String login(String studentID, String password, Activity activity) {
        try {
            String result = NetworkUtils.httpGet(String.format(UrlConstant.loginUrl, studentID, Base64.encodeToString(password.getBytes(), Base64.NO_WRAP)));
            if (result != null) {
                if (!result.contains("{") && !result.contains("}")) {
                    return result;
                }

                JSONTokener jsonTokener = new JSONTokener(result);
                JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
                String token = jsonObject.has("token") ? jsonObject.getString("token") : "";

                SharedPreferences sp = activity.getSharedPreferences("user", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.putString("studentID", studentID);
                editor.putString("token", token);
                editor.commit();

                Constant.STUDENT_ID = studentID;
                Constant.STUDENT_TOKEN = token;

                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
